<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | 基础模块（任务）数据控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\exception\LogicException;
use common\service\CountPendingService;
use common\service\DesignService;
use common\service\DismantleTaskService;
use common\service\EntityAbolitionOrEnableService;
use common\service\InsideTaskReviewWorkflowService;
use common\service\PersonalExecuteTaskListService;
use common\service\ProduceStatementReportService;
use common\service\ProjectOkrService;
use common\service\ShotService;
use common\service\StepSkuService;
use common\service\TaskAbolitionService;
use common\service\TaskAssignService;
use common\service\TaskCapacityService;
use common\service\TaskDocumentService;
use common\service\TaskGenerateService;
use common\service\TaskLibraryService;
use common\service\TaskLockService;
use common\service\TaskService;
use common\service\TaskStatisticsService;
use common\service\TaskUpstreamService;
use common\service\TimelogService;
use common\service\TodoService;
use common\service\TaskAssembleService;
use common\validate\CosMedia;
use common\validate\Task as TaskValidate;
use support\ErrorCode;
use think\Exception;
use think\Request;
use think\Response;
use Throwable;

class TaskController extends VerifyController
{
    protected $taskService;

    private $taskDocumentService;
    private $taskAssignService;
    private $todoService;
    private $insideTaskReviewWorkflowService;
    private $personalExecuteTaskListService;
    private $taskCapacityService;
    private $taskStatisticsService;
    private $taskGenerateService;
    private $stepSkuService;
    private $taskAssembleService;
    private $designService;
    private $taskAbolitionService;
    private $dismantleTaskService;
    private $taskUpstreamService;
    private $shotService;
    private $entityAbolitionOrEnableService;
    private $taskLockService;

    public function __construct()
    {
        parent::__construct();
        $this->taskService = TaskService::getInstance();
        $this->dismantleTaskService = DismantleTaskService::getInstance();
        $this->taskUpstreamService = TaskUpstreamService::getInstance();
        $this->taskDocumentService = TaskDocumentService::getInstance();
        $this->taskAssignService = TaskAssignService::getInstance();
        $this->insideTaskReviewWorkflowService = InsideTaskReviewWorkflowService::getInstance();
        $this->todoService = new TodoService();
        $this->personalExecuteTaskListService = PersonalExecuteTaskListService::getInstance();
        $this->taskCapacityService = TaskCapacityService::getInstance();
        $this->taskStatisticsService = new TaskStatisticsService();
        $this->taskGenerateService = TaskGenerateService::getInstance();
        $this->stepSkuService = StepSkuService::getInstance();
        $this->taskAssembleService = TaskAssembleService::getInstance();
        $this->designService = DesignService::getInstance();
        $this->taskAbolitionService = TaskAbolitionService::getInstance();
        $this->shotService = ShotService::getInstance();
        $this->entityAbolitionOrEnableService = EntityAbolitionOrEnableService::getInstance();
        $this->taskLockService = TaskLockService::getInstance();
    }

    /**
     * 组长分配工序任务 给团队内成员
     * @update 2021年7月21日 执行人用户id调整为saas user_id
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function setTaskStepExecutor(Request $request)
    {
        $param = $request->param();
        $validate = new TaskValidate();
        foreach ($param['tasks'] as $task) {
            if (!$validate->check($task, null, 'SetTaskStepExecutorItem')) {
                throw_strack_exception($validate->getError(), ErrorCode::SET_TASK_STEP_EXECUTOR_PARAM);
            }
        }

        $res = $this->taskService->setStepTaskExecutorBatch($param['tasks'], $request->getUserId(), $request->getTenantId());
        return json(success_response('', $res));
    }

    /**
     * 查询一种实体任务树
     * @param Request $request
     * @return Response
     */
    public function getEntityTaskTree(Request $request)
    {
        $param = $request->param()['param'];
        $onlyTotal = $param['only_total'] === "yes";
        $page = $param['page'] ?? [1, C("database.database_max_select_rows")];
        $resData = $this->taskService->getEntityTaskTree($param['filter'], $request->getModuleCode(), $page, $onlyTotal);
        return json($resData);
    }

    /**
     * 获取个人页面任务统计
     * @param Request $request
     * @return Response
     */
    public function getPersonalTaskStatistics(Request $request)
    {
        $resData = $this->taskService->getPersonalTaskStatistics($request->getUserId());
        return json(success_response('', $resData));
    }

    /**
     * 获取个人执行任务列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getPersonalExecuteTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $resData = $this->personalExecuteTaskListService->getPersonalExecuteTaskList($param['param'], $request->getUserId(), $request->getTenantId());
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取个人激活的时间日志
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getPersonalTaskActiveTimer(Request $request)
    {
        $resData = TimelogService::getInstance()->getPersonalTaskActiveTimer();
        return json(success_response('', $resData));
    }

    /**
     * 获得待分配的任务(step_category 类型)
     * @param Request $request
     * @return Response
     */
    public function getEntityTaskWaitForAssign(Request $request)
    {
        $param = $request->param()['param'];
        $projectId = $param['project_id'];
        $episodeId = $param['episode_id'] ?? 0;
        $taskIds = !empty($param['tasks']) ? explode(',', $param['tasks']) : [];
        $entityIds = !empty($param['entities']) ? explode(',', $param['entities']) : [];
        try {
            $res = $this->taskService->getStepCategoryTaskWaitForAssign($param['param'], $projectId, $episodeId, $taskIds, $entityIds);
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获得待分配的任务(step 类型)
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function getStepTaskWaitForAssign(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getStepTaskWaitForAssign($param['param'], $request->getUserId());
        return json(success_response('', $res));
    }

    /**
     * 获得组长的任务树
     * (normal sub 类任务 执行人/分配人 是自己)
     * @param Request $request
     * @return Response
     */
    public function getTeamLeaderTaskTree(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getTeamLeaderTaskTree($param, $request->getUserId(), $request->getTenantId());
        return json($res);
    }

    /**
     * 查询任务的工序流配置
     * @param Request $request
     * @return Response
     */
    public function getTaskStepWorkflowConfig(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskService->getTaskStepWorkFlowNetwork($param['param']);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询任务详情
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTaskDetail(Request $request): Response
    {
        try {
            $param = $request->param();
            $res = $this->taskService->getTaskDetail($param['param']);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 通过工序分类code查询一种实体任务树
     * 通过分类来分组任务
     * @param Request $request
     * @return Response
     */
    public function getTaskTreeByStepCategoryCode(Request $request)
    {
        $param = $request->param();
        $param['param']['only_total'] = $param['param']['only_total'] ?? 'no';
        $onlyTotal = $param['param']['only_total'] === "yes";
        $page = $param['param']['page'] ?? [1, C("database.database_max_select_rows")];
        $filter = $param['param']['filter'];
        $resData = $this->taskService->getTaskTreeGroupByStepCategory($filter, $onlyTotal, $page);
        if ($onlyTotal) {
            return json(success_response('', ['total' => $resData]));
        } else {
            return json($resData);
        }
    }

    /**
     * 更新任务的开始/结束时间
     * @param Request $request
     * @return Response
     */
    public function updateSEDate(Request $request)
    {
        $param = $request->param();
        $validate = new TaskValidate();
        $validate->scene('UpdateSEDateItem');
        foreach ($param['data'] as $taskItem) {
            if (!$validate->check($taskItem)) {
                throw_strack_exception($validate->getError(), ErrorCode::UPDATE_TASK_END_START_DATE_PARAM);
            }
        }
        try {
            $res = $this->taskService->updateSEDateBatch($param['data']);
            return json(success_response('', $res));
        } catch (Throwable $e) {
            $code = $e->getCode() >= 0 ? "-{$e->getCode()}" : $e->getCode();
            throw_strack_exception($e->getMessage(), $code);
        }
    }

    /**
     * 查询任务审核点 包含当前任务审核进度
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getCheckListWithProgress(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getCheckListWithProgress($param['param']);
        return json(success_response("", $res));
    }

    /**
     * 查询任务审批流
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function selectReview(Request $request)
    {
        $param = $request->param();
        $taskId = $param['param']['filter']['task_id'];
        try {
            $res = $this->insideTaskReviewWorkflowService->selectReview($taskId, $request->getUserId());
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询标记的任务检查点
     * @param Request $request
     * @return Response
     */
    public function getMarkedCheckList(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getMarkedCheckList($param['param']);
        return json(success_response('', $res));
    }

    /**
     * 查询一个待提交的任务检查点
     * @param Request $request
     * @return Response
     */
    public function getLatestCheckItem(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getLatestCheckItem($param['param']);
        return json(success_response('', $res));
    }

    /**
     * 当前用户部门的工时统计
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTeamTaskManHourStatistics(Request $request)
    {
        $param = $request->param();
        $res = $this->taskStatisticsService->getTeamTaskManHourStatistics($param, $request->getUnionUserId());
        return json(success_response("", $res));
    }

    /**
     * 获取页面任务统计
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTaskStatistics(Request $request)
    {
        $param = $request->param();
        $resData = $this->taskStatisticsService->getTaskStatistics($param, $request->getUserId(), $request->getUnionUserId());
        return json(success_response('', $resData));
    }

    /**
     * 获取异常任务列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function selectAbnormalTaskList(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->selectAbnormalTaskList($param['role_code'], $param['param'], $request->getUserId());
        return json(success_response('', $res));
    }

    /**
     * 获取任务分类统计
     * @param Request $request
     * @return Response
     */
    public function getTaskCategoryStatistics(Request $request)
    {
        $param = $request->param();
        $resData = $this->taskService->getTaskCategoryStatistics($param);
        return json(success_response('', $resData));
    }

    /**
     * 查询待办
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function selectTodo(Request $request)
    {
        $param = $request->param();
        $resData = $this->todoService->selectTodo($param['param']);
        return json(success_response('', $resData));
    }

    /**
     * 创建待办
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function createTodo(Request $request)
    {
        $param = $request->param();
        $resData = $this->todoService->createTodo($param['data']);
        return json(success_response('', $resData));
    }

    /**
     * 更新待办
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function updateTodo(Request $request)
    {
        $param = $request->param();
        $resData = $this->todoService->updateTodo($param['data']);
        return json(success_response('', $resData));
    }

    /**
     * 获取任务实际工时
     * @param Request $request
     * @return Response
     */
    public function getTaskActiveManHour(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getTaskActiveManHour($param['param']);
        return json(success_response("", $res));
    }

    /**
     * 更新任务开始/结束时间 通过实体id
     * @param Request $request
     * @return Response|void
     * @throws Exception
     * @throws Throwable
     */
    public function updateTaskDateByEntity(Request $request)
    {
        try {
            $param = $request->param();
            $res = $this->taskService->updateTaskDateByEntity($param['param']);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获得未通过的审核点
     * @param Request $request
     * @return Response
     */
    public function getUndoCheckItem(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getMarkedCheckList($param['param']);
        return json(success_response('', $res));
    }


    /**
     * 获取指定项目任务全生命周期统计数据
     * @param Request $request
     * @return Response
     */
    public function getProjectTaskAllLifeCycleStatistics(Request $request)
    {
        $param = $request->param();
        $res = $this->taskStatisticsService->getProjectTaskAllLifeCycleStatisticsByCache($param['param']['filter'], $param['type']);

        return json(success_response('', $res));
    }

    /**
     * 获取当前全生命周期缓存状态
     * @param Request $request
     * @return Response
     */
    public function getProjectEpisodeTaskStatisticsStatus(Request $request)
    {
        $param = $request->param();
        $res = $this->taskStatisticsService->getProjectEpisodeTaskStatisticsStatus($param['project_id']);

        return json(success_response('', $res));
    }

    /**
     * 刷新当前全生命周期缓存
     * @param Request $request
     * @return Response
     */
    public function refreshProjectEpisodeTaskStatisticsCache(Request $request)
    {
        $param = $request->param();
        $res = $this->taskStatisticsService->refreshProjectEpisodeTaskStatisticsCache($param['project_id']);

        return json(success_response('', $res));
    }

    /**
     * 获取搜索列表
     * @param Request $request
     * @return Response
     */
    public function getProjectTaskAllLifeCycleStatisticsSearchList(Request $request)
    {
        $param = $request->param();

        $filter = [];
        if (array_key_exists('param', $param)) {
            $filter = $param['param']['filter'];
        }

        // 从镜头展开
        if ($param['type'] === 'shot') {
            $res = $this->taskStatisticsService->getProjectTaskAllLifeCycleStatisticsSearchListByShot($param['project_id'], $filter);
        } else {
            $res = $this->taskStatisticsService->getProjectTaskAllLifeCycleStatisticsSearchListByAsset($param['project_id'], $filter);
        }

        return json(success_response('', $res));
    }

    public function getLifeCycleStatisticsEntityTask(Request $request)
    {
        $param = $request->param();

        // 从镜头展开
        if ($param['type'] === 'shot') {
            $res = $this->taskStatisticsService->getLifeCycleStatisticsEntityTaskByShot($param['param']);
        } else {
            $res = $this->taskStatisticsService->getLifeCycleStatisticsEntityTaskByAsset($param['param']);

        }

        return json(success_response('', $res));
    }


    /**
     * 获取指定项目OkR 统计
     * @param Request $request
     * @return Response
     */
    public function getProjectOkr(Request $request)
    {
        $param = $request->param();
        $projectOkrService = new ProjectOkrService();
        $res = $projectOkrService->getOkrStatistics($param['param']);
        return json(success_response('', $res));
    }

    /**
     * 自动生成集数任务
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function autoGenerateEpisodesTask(Request $request)
    {
        $param = $request->param();
        $res = $this->taskGenerateService->autoGenerateEpisodesTask($param['param']['filter']['project_id']);
        return json(success_response('', $res));
    }

    /**
     * 执行中任务列表 通过分类分组
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getExecutingTaskListGroupByStepCategory(Request $request)
    {
        $res = $this->taskService->getExecutingTaskListGrouped($request->param(), $request->getUserId(), $request->getModuleCode());
        return json(success_response('', $res));
    }

    /**
     * 查询待分配的任务列表 通过分类分组
     * @param Request $request
     * @return Response
     */
    public function getStepTaskWaitForAssignGroupByStepCategory(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getStepTaskWaitForAssignGroupByStepCategory($param['param'], $request->getUserId(), $request->getTenantId());
        return json(success_response('', $res));
    }

    /**
     * 审片室 当前版本任务审核点
     * @param Request $request
     * @return Response
     */
    public function getTaskVersionCheckList(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getTaskVersionCheckList($param['param']);
        return json(success_response("OK", $res));
    }

    /**
     * 任务能否开始检查
     * @param Request $request
     * @return Response|void
     * @throws Exception
     */
    public function taskCanStart(Request $request)
    {
        try {
            $param = $request->param();
            $res = $this->taskService->taskCanStart($param['param']['task_id']);
            return json(success_response("OK", $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 任务更新
     * @param Request $request
     * @return Response
     */
    public function update(Request $request)
    {
        return parent::update($request);
    }

    /**
     * 任务产能统计
     * @return Response
     */
    public function certCount(Request $request)
    {
        $res = $this->taskCapacityService->certCount($request->param(['param']));
        return json(success_response("OK", $res));
    }

    /**
     * 工序任务工序标准查询
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function stepTaskStandard(Request $request)
    {
        $res = $this->taskService->stepTaskStandard($request->param()['param']);
        return json(success_response("OK", $res));
    }

    /**
     * 已完成任务列表分组
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getDoneTaskListGrouped(Request $request)
    {
        $res = $this->taskService->getDoneTaskListGrouped($request->param(), $request->getUserId(), $request->getModuleCode());
        return json(success_response('', $res));
    }

    /**
     * 更新版本打包名称
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function updateLatestVersionPackName(Request $request): Response
    {
        $res = $this->taskService->updateLatestVersionPackName($request->param()['data']);
        return json(success_response('OK', $res));
    }

    /**
     * 受影响任务数量
     * @param Request $request
     * @return Response
     */
    public function getEffectedTaskCount(Request $request): Response
    {
        $res = $this->taskUpstreamService->getEffectedTaskCount($request->param()['param']['id']);
        return json(success_response('OK', $res));
    }

    /**
     * 查询上游任务最新版本的下载信息
     * @param Request $request
     * @return Response
     * @throws Exception|\Exception
     */
    public function getUpstreamLatestFileShareInfo(Request $request): Response
    {
        $res = $this->taskUpstreamService->getUpstreamLatestFileShareInfo($request->param()['param']['id']);
        return json(success_response('OK', $res));
    }

    /**
     *  任务就绪
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function ready(Request $request): Response
    {
        try {
            $res = $this->taskService->ready($request->param()['param']['id']);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 是否工序流上一个工序分类 工序任务是否完成
     * @param Request $request
     * @return Response
     */
    public function isPreStepCategoryStepTaskDone(Request $request): Response
    {
        $res = $this->taskService->isPreStepCategoryStepTaskDone($request->param()['param']['task_id']);
        return json(success_response('OK', $res));
    }

    /**
     * 获取当前点击的实体的工序流数据
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getEntityStepWorkflow(Request $request)
    {
        $param = $request->param();
        $taskId = $param['param']['filter']['task_id'] ?? 0;
        $stepCategoryId = $param['param']['filter']['step_category_id'] ?? 0;
        $res = $this->taskService->getEntityStepWorkflow($param['param']['filter']['entity_id'], $stepCategoryId, $taskId);
        return json(success_response('OK', $res));
    }

    /**
     * 获取实体工序详情
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getEntityStepTaskDetails(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getEntityStepTaskDetails($param['param']['filter']['entity_id'], $param['param']['filter']['task_id']);
        return json(success_response('OK', $res));
    }

    /**
     * 获取多个实体任务二级工序详情信息
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getEntityStepCategoryTask(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->getEntityStepCategoryTask($param['param']['filter']['entity_task']);
        return json(success_response('OK', $res));
    }

    /**
     * 任务上游关系查询
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function getUpstreamRelationInfo(Request $request): Response
    {
        $param = $request->param();
        $res = $this->taskUpstreamService->getUpstreamRelationInfo($param['param']);
        return json(success_response('OK', $res));
    }

    /**
     * 设置工序任务分配人
     * @param Request $request
     * @return Response
     * @throws Throwable
     * @throws Exception
     */
    public function setStepTaskAssigneeBatch(Request $request): Response
    {
        $param = $request->param();
        $validate = new TaskValidate();
        foreach ($param['tasks'] as $task) {
            if (!$validate->check($task, null, 'setStepTaskAssigneeItem')) {
                throw_strack_exception($validate->getError(), ErrorCode::SET_TASK_STEP_EXECUTOR_PARAM);
            }
        }
        $res = $this->taskService->setStepTaskAssigneeBatch($param['tasks'], $request->getUserId());
        return json(success_response('OK', $res));
    }

    /**
     * 获得任务的设计需求和媒体信息
     * @param Request $request
     * @return Response
     */
    public function getSourceDesignRequirementsWithMedia(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskService->getSourceDesignRequirementsWithMedia($param['param']['filter']['id']);
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询任务动态筛选条件
     * @param Request $request
     * @return Response
     */
    public function getDynamicTaskListFilter(Request $request)
    {
        try {
            $param = $request->param();
            $dataFilter = $request->param()['param']['data_filter'] ?? 'myself_task_list';
            $res = $this->taskService->getDynamicTaskListFilter($request->getUserId(), $request->getUnionUserId(), $request->getTenantId(), $param, $dataFilter, $request->getModuleCode());
            return json(success_response('OK', $res));
        } catch (Throwable $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询待分配的任务列表 高级版
     * @param Request $request
     * @return Response
     */
    public function getStepTaskWaitForAssignPrime(Request $request)
    {
        $param = $request->param();
        $res = $this->taskAssignService->getStepTaskWaitForAssignPrime($param['param'], $request->getUserId(), $request->getTenantId());
        return json(success_response('', $res));
    }

    /**
     * 查询可分配的供应商树
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getCanAssignSupplierTaskTree(Request $request)
    {
        try {
            $res = $this->taskAssignService->getCanAssignSupplierTaskTree($request->param()['param'], $request->getTenantId());
            return json($res);
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询分配中任务的的供应商树
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getAssigningSupplierTaskTree(Request $request)
    {
        $res = $this->taskAssignService->getAssigningSupplierTaskTree($request->param()['param'], $request->getTenantId());
        return json(success_response('OK', $res));
    }

    /**
     * 分配任务给供应商
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function assignTaskToSupplierBatch(Request $request)
    {
        $param = $request->param();
        $data = $param['data'];
        try {
            $validate = new TaskValidate();
            $validate->scene('AssignTaskToSupplierItem');
            foreach ($data as $item) {
                if (!$validate->check($item)) {
                    throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
                }
            }

            $res = $this->taskAssignService->assignTaskToSupplierBatch($data, $request->getUserId(), $request->getTenantId());
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 确认分配
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function ensureAssignBatch(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->ensureAssignBatch($param['param']);
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 等待接收的资产任务列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function waitConfirmAssetTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->waitConfirmAssetTaskList($param['param'], $request->getUserId(), $request->getTenantId());
            return json($res);
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 等待接收的镜头任务列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function waitConfirmShotTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->waitConfirmShotTaskList($param['param'], $request->getUserId(), $request->getTenantId());
            return json($res);
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询任务工序标准文档
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTaskStepStandardDocument(Request $request)
    {
        try {
            $param = $request->param();
            $res = $this->taskDocumentService->getTaskStepStandardDocument($param['param']['filter']['id']);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 处理待接收的让你无列
     * @param Request $request
     * @return Response|void
     * @throws \Exception
     */
    public function handleWaitConfirmTask(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->handleWaitConfirmTask($param['param'], $request->getUserId());
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }


    /**
     * 确认的镜头任务
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function acceptedShotTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->acceptedShotTaskList($param, $request->getTenantId());
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 确认的资产任务
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function acceptedAssetTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->acceptedAssetTaskList($param, $request->getTenantId());
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取组员以分配的任务列表
     * @param Request $request
     * @return Response|void
     * @throws \Exception
     */
    public function getArtistTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskAssignService->getArtistTaskList($param['param'], $request->getUnionUserId());
            return json($res);
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 更新任务排期时间
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function updateTaskScheduleDate(Request $request)
    {
        try {
            $res = $this->taskAssignService->updateTaskScheduleDate($request->param()['data']);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 撤回任务
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function revokeTaskAssigneeStatus(Request $request)
    {
        try {
            $res = $this->taskAssignService->revokeTaskAssigneeStatus($request->param()['param']['filter'], $request->getTenantId());
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询待分配统计 (任务分类分组数据)
     * @param Request $request
     * @return Response
     */
    public function getWaitAssignStepCategoryCount(Request $request)
    {
        $res = $this->taskAssignService->getWaitAssignStepCategoryCount($request->param()['param']['filter'], $request->param()['param']['module_code']);
        return json(success_response('OK', $res));
    }

    /**
     * 计算任务工时
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function calculateTaskManHour(Request $request)
    {
        try {
            $res = $this->stepSkuService->calculateTaskManHour($request->param()['param']['task_id']);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 任务列表
     * @param Request $request
     * @return Response
     */
    public function getTaskList(Request $request)
    {
        $param = $request->param()['param'];
        try {
            $res = $this->taskAssignService->getTaskList($param, $request->getTenantId());
            return json(success_response('OK', $res));
        } catch (\Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 一键完成
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function quickDone(Request $request)
    {
        $dataList = $request->param()['data_list'];
        $validate = new TaskValidate();
        foreach ($dataList as $task) {
            if (!$validate->check($task, null, 'quickDoneItem')) {
                throw_strack_exception($validate->getError(), ErrorCode::DATA_INVALID);
            }
        }
        try {
            $res = $this->taskAssignService->quickDone($dataList, $request->getUserId(), $request->getTenantId());
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询任务关联map
     * @param Request $request
     * @return Response
     */
    public function queryTaskRelationMap(Request $request)
    {
        try {
            $res = $this->taskService->queryTaskRelationMap($request->param()['param']['filter']['id']);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 分配任务给部门
     * @param Request $request
     * @return Response|void
     * @throws \Exception
     */
    public function batchSetStepTaskDepartmentId(Request $request)
    {

        $param = $request->param();
        $validate = new TaskValidate();
        foreach ($param['data_list'] as $data) {
            if (!$validate->check($data, null, 'BatchSetStepTaskDepartmentIdItem')) {
                throw_strack_exception($validate->getError(), ErrorCode::DATA_INVALID);
            }
        }

        try {
            $res = $this->taskAssignService->batchSetStepTaskDepartmentId($param['project_id'], $param['data_list'], $request->getUserId());
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询订单重新分配任务列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getOrderReassignTaskList(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->taskAssignService->getOrderReassignTaskList($param);
        return json(success_response('OK', $res));
    }

    /**
     * 获取任务组装信息
     * @param Request $request
     * @return Response
     */
    public function getTaskAssembleInfo(Request $request)
    {
        $res = $this->taskAssembleService->getTaskAssembleInfo($request->param()['param']['filter']['id']);
        return json(success_response('OK', $res));
    }

    /**
     * 任务组装回调
     * @param Request $request
     * @return Response|void
     * @throws Exception
     */
    public function taskAssembleCallback(Request $request)
    {
        try {
            $res = $this->taskAssembleService->taskAssembleCallback($request->param()['param']['filter']['id']);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取任务 assign_task（任务分配）、review_submit（任务审核提交）、review_submit_feedback（任务审核反馈审核） 的小红点提示数据
     * @param Request $request
     * @return Response
     */
    public function getTaskCountData(Request $request)
    {
        $param = $request->param();
        $taskAssembleService = new CountPendingService();
        $filter = !empty($param['filter']) ? $param['filter'] : [];
        $res = $taskAssembleService->getTaskCountData($param['type'], $param['project_id'], $filter);
        return json(success_response('OK', $res));
    }

    /**
     * 同步任务状态到外包源任务
     * @param Request $request
     * @return Response
     */
    public function syncTaskStatusToSourceTask(Request $request)
    {
        $res = $this->taskService->syncTaskStatusToSourceTask($request->param()['param']['id']);
        return json(success_response('OK', $res));
    }

    /**
     * 分配任务撤回
     * @param Request $request
     * @return Response|void
     * @throws Throwable
     */
    public function assignWithdraw(Request $request)
    {
        try {
            $res = $this->taskAssignService->assignWithdraw($request->param()['param']['filter'], $request->getUserId());
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取资产工序任务全生命周期
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function getAssetStepTaskAllLifeCycle(Request $request)
    {
        try {
            $res = $this->taskStatisticsService->getAssetStepTaskAllLifeCycle($request->param(), $request->getTenantId(), $request->getUserId());
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取镜头工序任务全生命周期
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function getShotStepTaskAllLifeCycle(Request $request)
    {
        $param = $request->param();
        $res = $this->taskStatisticsService->getShotStepTaskAllLifeCycle($param, $request->getTenantId(), $request->getUserId());
        return json(success_response('OK', $res));
    }

    /**
     * 获取全生命周期相关数据统计
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function taskAllLifeCycleLinkDataCount(Request $request)
    {
        $param = $request->param()["param"];
        $filter = $param['filter'];
        $res = $this->taskStatisticsService->taskAllLifeCycleLinkDataCount($filter);
        return json(success_response('OK', $res));
    }

    /**
     * 修改执行人
     * @param Request $request
     * @return Response
     * @throws Exception
     * @throws Throwable
     */
    public function changeExecutor(Request $request)
    {
        try {
            $data = $request->param()["data"];
            $res = $this->taskAssignService->changeExecutor($data);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 任务组转检查
     * @param Request $request
     * @return Response|void
     */
    public function checkTaskCanAssemble(Request $request)
    {
        try {
            $res = $this->taskAssembleService->checkTaskCanAssemble($request->param()['param']['id']);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 资产 废除-启用
     * @param Request $request
     * @return Response|void
     * @throws Throwable
     */
    public function taskStatus(Request $request)
    {
        try {
            $param = $request->param();
            $res = $this->entityAbolitionOrEnableService->entityAbolitionOrEnabling($param['data']['status'], $param['data']);
//            $res = $this->taskService->TaskAbolitionOrEnabling($param['data']['status'], $param['data']);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询任务审批流
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getUserReviewWorkFlow(Request $request)
    {
        $param = $request->param()['param'];
        try {
            $res = $this->insideTaskReviewWorkflowService->getUserReviewWorkFlow($param, $request->getUserId());
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取多个任务的版本检查点
     * @param Request $request
     * @return Response
     */
    public function getMarkedMultipleCheckList(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->taskService->getMarkedMultipleCheckList($param);
        return json(success_response('', $res));
    }

    /**
     * 拆分任务
     * @param Request $request
     * @return Response
     * @throws \Exception|Throwable
     */
    public function dismantleSetStepTask(Request $request)
    {
        $param = $request->param();
        $data = $param['data'];
        try {
            $res = $this->dismantleTaskService->dismantleSetStepTask($data);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     *  删除子任务
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function deleteDismantleTask(Request $request)
    {
        $param = $request->param();
        $data = $param['data'];
        $res = $this->dismantleTaskService->deleteDismantle($data['id']);
        return json(success_response('OK', $res));
    }

    /**
     * 概念图片版本信息
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function designVersions(Request $request)
    {
        $param = $request->param();
        $data = $param['param'];
        $res = $this->designService->designVersions($data['task_id']);
        return json(success_response('OK', $res));
    }

    /**
     * 获取已开始后的关联模型任务
     * @param Request $request
     * @return Response
     */
    public function selectRelateModelTask(Request $request)
    {
        $param = $request->param();
        $res = $this->taskService->selectRelateModelTask($param['param']);
        return json(success_response('OK', $res));
    }

    /**
     * 获取上游实体任务
     * @param Request $request
     * @return Response
     */
    public function getAllUpstreamEntityTask(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->taskUpstreamService->getAllUpstreamEntityTask($param["filter"]["task_id"]);
        return json(success_response('OK', $res));
    }


    /**
     * 设置过程文件
     * @param Request $request
     * @return Response|void
     * @throws \Exception
     */
    public function setProcessFile(Request $request)
    {
        $param = $request->param();
        $mediaValidate = new CosMedia();
        $mediaValidate->scene('CreateMedia');

        if (!$mediaValidate->check($param['data']['cos_media'])) {
            throw_strack_exception($mediaValidate->getError(), ErrorCode::CREATE_MEDIA_PARAM);
        }

        try {
            $res = $this->taskService->setProcessFile($param['data'], $request->getUserId());
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取过程文件
     * @param Request $request
     * @return Response|void
     * @throws \Exception
     */
    public function selectProcessFile(Request $request)
    {
        $param = $request->param();
        try {
            $res = $this->taskService->getProcessFile($param);
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 废除
     * @param Request $request
     * @return Response|void
     * @throws Throwable
     */
    public function deprecated(Request $request)
    {
        $param = $request->param();
        $taskId = $param['param']['task_id'];
        $isEnable = $param['param']['is_enable'] === 'yes';
        try {
            $res = $this->taskAbolitionService->deprecated($taskId, $isEnable, $request->getUserId());
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取更新时间任务树
     * @param \think\Request $request
     * @return \think\Response
     */
    public function getPopUpdateTimeTaskTree(Request $request)
    {
        $filter = $request->param()['param']['filter'];
        $resData = $this->shotService->getPopUpdateTimeTaskTree($filter['task_ids']);
        return json(success_response('', $resData));
    }

    /**
     * 开关任务锁
     * @return \think\Response
     * @throws \think\Exception
     */
    public function switchTaskLock(Request $request)
    {
        $data = $request->param()['data'];
        try {
            $resData = $this->taskLockService->switchTaskLock($data['task_ids'], $data['is_lock']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }

    }

    /**
     * 生产信息简报
     * @param Request $request
     * @return Response
     */
    public function productionInfoReport(Request $request)
    {
        $param = $request->param()['param'];
        $startTime = $param['start_time'];
        $endTime = $param['end_time'];
        $res = ProduceStatementReportService::getInstance()->productionInfoReport($param['project_id'], $startTime, $endTime);
        $episodeList = array_unique(array_column($res, 'episode_name'));
        $episodeWeekMap = [];
        $dayEpisodeMap = [];
        foreach ($episodeList as $episodeName) {
            foreach (get_month_day_list($startTime, $endTime) as $day) {
                $episodeWeekMap[$episodeName]['episode_name'] = $episodeName;
                $dayEpisodeMap[$episodeName][] = $day;
            }
        }
        foreach ($res as $item) {
            foreach ($dayEpisodeMap[$item['episode_name']] as $day) {
                $nowDayTIme = strtotime($day);
                $week = date('w', strtotime($day)) == '0' ? 7 : date('w', strtotime($day));
                if (empty($episodeWeekMap[$item['episode_name']]['week' . $week])) {
                    $episodeWeekMap[$item['episode_name']]['week' . $week] = [];
                }
                if ($item['plan_start_time'] <= $nowDayTIme && $nowDayTIme <= $item['plan_end_time']) {
                    $episodeWeekMap[$item['episode_name']]['week' . $week][] = $item;
                }
            }
        }
        $episodeWeekMap = array_values($episodeWeekMap);
        return json(success_response('', $episodeWeekMap));
    }

    /**
     * 获取拆分资产数据
     * @param Request $request
     * @return Response
     */
    public function getAssetDataList(Request $request)
    {
        $param = $request->param()['param'];
        $entity_id = $param['entity_id'] ?? 0;
        $result = TaskService::getInstance()->getAssetDataList($entity_id);

        return json(success_response('', $result));
    }

    /**
     * 任务资产数据
     * @param Request $request
     * @return void
     */
    public function getJsonReferenceAsset(Request $request)
    {
        $param = $request->param()['param'];

        $result = TaskService::getInstance()->getJsonReferenceAsset($param);
        return json(success_response('操作成功', $result));
    }

    /**
     * 检查发布任务是否有子任务未完成
     * @param Request $request
     * @return true fasle
     */
    public function checkWhetherExistUnfinishedSubtask(Request $request)
    {
        $taskId = (int)$request->param()['task_id'];
        $result = TaskService::getInstance()->checkWhetherExistUnfinishedSubtask($taskId);
        return json(success_response('success', $result));
    }


    /**
     * 获取任务使用的工序流
     * @param Request $request
     * @return Response
     */
    public function getTaskUseStepWorkflowList(Request $request): Response
    {
        $taskIds = $request->param()['task_ids'] ?? [];
        $result = TaskService::getInstance()->getTaskUseStepWorkflowList($taskIds);
        return json(success_response('success', $result));
    }

    /**
     * 获取每日交付率
     * @param Request $request
     * @return Response
     */
    public function getDailyDeliveryTaskList(Request $request): Response
    {
        $param = $request->param()['param'] ?? [];

        $projectId = $param['project_id'] ?? 0;
        $deliveryTime = $param['delivery_time'] ?? [0, 0];
        $result = TaskService::getInstance()->getDailyDeliveryTaskList($projectId, $deliveryTime);
        return json(success_response('success', $result));
    }
}
